package cn.kgc.crowdfundingadmin.controller;

import cn.kgc.crowdfundingadmin.common.ResultEntity;
import cn.kgc.crowdfundingadmin.pojo.Menu;
import cn.kgc.crowdfundingadmin.service.MenuService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuController {

    @Resource
    MenuService menuService;


    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
// 1.查询所有的树形节点用于组装
        List<Menu> menuList = menuService.getAll();
        // 2.将List<Menu>转换为Map<Menu的id,Menu>
        Map<Integer,Menu> menuMap = new HashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(),menu);
        }

        // 3.声明变量用于存储根节点对象
        Menu rootNode = null;

        for (Menu menu : menuList) {
            //是父节点
            if (menu.getPid()==null){
                rootNode=menu;
                continue;
            }
            //是子节点从menuMap找到父节点，并添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);
        }
        return ResultEntity.successWithoutData(rootNode);
    }

    @RequestMapping("/menu/save")
    public ResultEntity<String> saveMenu(Menu menu) {

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();
    }

    //根据id查询
    @RequestMapping("/menu/get/{menuId}")
    public ResultEntity<Menu> getMenuById(@PathVariable("menuId") Integer menuId) {
        Menu menu = menuService.getMenuById(menuId);

        return ResultEntity.successWithoutData(menu);
    }

    //修改
    @RequestMapping("/menu/update")
    public ResultEntity<String> update(Menu menu){
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    //删除
    @RequestMapping("/menu/delete/{menuId}")
    public ResultEntity<String> delete(@PathVariable("menuId") Integer menuId) {
        menuService.batchRemove(menuId);
        return ResultEntity.successWithoutData();
    }

}
